<?php

namespace app\store\controller\zzindb;

use alibabasdk\AlibabaClient;
use alibabasdk\AlibabaException;
use think\Config;
use think\Db;
use think\Request;
use think\View;

class Aligoods extends Alibasecontroller
{
    private $myType = [
        0=>[
            'mianstr'=>'1813***精品玩具***0***1','sonstrarr'=>[
                '1045520***运动休闲***0***1','181309***益智科教***0***1','122988002***公仔玩偶***0***1','122962001***电动遥控***0***1',
                '181302***模型玩具***0***1','201565322***音乐玩具***0***1','122990003***新奇特玩具***0***1','124022002***发光玩具***0***1',
                '201160102***娃娃玩具***0***1','127002083***积木拼插类玩具***0***1','1048131***充气玩具***0***1','1045593***其他类玩具***1***3',
                '201161304***毛绒公仔***0***1',
            ]
        ],
        1=>[
            'mianstr'=>'67***文具办公***0***1','sonstrarr'=>[
                '2111***学习文具***0***1','10336***纸品本册***0***1','2113***桌面用品***0***1',
                '81***书写工具***0***1','2127***书法绘图***0***1','125064004***文化用品***0***1','1045523***电子产品***0***1',
                '1045647***学习书籍***0***1','2112***办公用纸***0***1','2122***办公收纳***0***1','2121***财务用品***0***1',
                '124904001***行政用品***0***1','201857705***手账***0***1','201305307***创意礼品***0***1','201229008***商务礼品***0***1','122192001***布置用品***0***1',
                '201162103***仿真花草***0***1','1702***节庆用品***0***1','201303011***动漫影视***0***1',
            ]
        ],
//        2=>[
//            'mianstr'=>'2***食品酒水***0***1','sonstrarr'=>[
//                '124744016***果干蜜饯***0***1','124734016***坚果炒货***0***1','124736016***糕点点心***0***1',
//                '124734017***饼干膨化***0***1','124746011***糖果***0***1','124742009***肉类零食***0***1',
//                '124742010***水产零食***0***1','124742011***即食豆制品***0***1','124744009***固态乳制品***0***1',
//                '10041***茶叶***0***1','10071***酒类***0***1','1048224***传统滋补***0***1','201164002***药食同源***0***1',
//                '201164102***冲调饮品***0***1',
//            ]
//        ],
//        3=>[
//            'mianstr'=>'7***数码电脑***0***1','sonstrarr'=>[
//                '123754001***智能设备***0***1','727***数码产品***0***1','1032228***数码配件***0***1','124776003***摄影摄像***0***1',
//                '1046693***苹果配件***0***1','728***手机通讯***0***1','50911***手机配件***0***1','10262***电脑外设***0***1',
//                '1046688***平板配件***0***1','1044130***手机饰品***0***1',
//            ]
//        ],
//        4=>[
//            'mianstr'=>'6***家用电器***0***1','sonstrarr'=>[
//                '1047889***迷你手持扇***1***3',
//                '1047104***影音电器***0***1','652***生活电器***0***1','1047981***两季电器***0***1','123610009***个护电器***0***1',
//                '653***厨房电器***0***1','1047893***保健电器***0***1','201571222***母婴电器***0***1',
//            ]
//        ],
//        5=>[
//            'mianstr'=>'1556***居家百货***0***1','sonstrarr'=>[
//                '1513***纸品湿巾***0***1','122196011***衣物清洁***0***1','201231505***女性护理***0***1','10313***美发产品***0***1',
//                '122194007***芳香用品***0***1','201303409***消毒抑菌***0***1', '1532***日用百货***1***3','1043058***身体清洁***0***1',
//                '122268004***口腔清洁***0***1','1043961***居家常用***1***3','1043789***日常护理***1***3','122212003***厨卫清洁剂***0***1',
//                '122262003***家居清洁护理***0***1','122522004***一次性用品***1***3','1043956***鞋用品***1***3','201774702***针线盒***1***3',
//            ]
//        ],
//        6=>[
//            'mianstr'=>'97***美容护肤***0***1','sonstrarr'=>[
//                '1042634***面部护理***0***1','201308710***面膜***0***1','201308310***面部精华***0***1','201303117***眼部护理***0***1',
//                '1043498***唇部护理***0***1','121702001***男士护肤***0***1','82101***面部彩妆***0***1','201304705***唇部彩妆***0***1',
//                '201307604***眼部彩妆***0***1','201303115***香水***0***1','1043171***美妆工具***0***1','201307015***美容仪器***0***1',
//                '1043162***美甲产品***0***1',
//            ]
//        ],
//        7=>[
//            'mianstr'=>'96***家纺家饰***0***1','sonstrarr'=>[
//                '127888009***创意摆件***0***1','127926016***装饰挂画***0***1','1043469***壁饰***0***1','1704***贴饰***0***1',
//                '1906***装饰框架***0***1','201148907***一次性巾类***0***1','121188018***婴童家纺***0***1','127926017***毛巾面巾***0***1',
//                '10132***床单套件***0***1','127900016***地毯地垫***0***1',
//            ]
//        ],
//        8=>[
//            'mianstr'=>'201547801***餐厨饮具***0***1','sonstrarr'=>[
//                '1046721***饮水用具***0***1','10287***餐具***0***1','122548001***锅煲***0***1','121548001***茶具***0***1',
//                '122320004***酒具***0***1','122146001***厨房工具***0***1','10297***烘焙用具***0***1',
//            ]
//        ],
//        9=>[
//            'mianstr'=>'1042954***箱包皮具***0***1','sonstrarr'=>[
//                '122228002***钱包***0***1','201997401***功能小包***0***1','124016002***女士包袋***0***1','201558112***口红包***1***3',
//                '121658001***男士包袋***0***1','122218002***手机包***1***3','201548701***电脑包包***0***1',
//                '201956604***双肩背包***0***1', '201556615***休闲箱包***0***1','122216001***旅行包袋***1***3','125728001***化妆箱包***0***1',
//            ]
//        ],
//        10=>[
//            'mianstr'=>'122916002***汽车用品***0***1','sonstrarr'=>[
//                '1212***影音导航***0***1','92***汽车内饰用品***0***1','3312***车载电器***0***1','79***汽车养护***0***1',
//            ]
//        ],
    ];
    /** 商品分类初始化界面 */
    public function index(){
        $type = $this->myType;
        $num11 = 0;
        $num22 = 0;
        foreach($type as $value){
            $num11++;
            $mainStrArr = explode('***', $value['mianstr']);
            echo '<div style="color:#F00;">'.$num11.'：'.$mainStrArr[1].'（'.$mainStrArr[0].'）</div>';
            foreach($value['sonstrarr'] as $value22){
                $sonStrArr = explode('***', $value22);
                $num22++;
                $sss = '<div style="padding-left:100px;padding-top:5px;">';
                //$sss .= '<span><a href="/index.php?s=/store/zzindb.aligoods/getGoodList/typepid/'.$mainStrArr[0].'/type/'.$sonStrArr[0].'/page/1" target="_blank">'.$num22.'：'.$sonStrArr[1].'</a>（'.$sonStrArr[0].'）</span>';
                $sss .= '<span>'.$num22.'：'.$sonStrArr[1].'（'.$sonStrArr[0].'）</span>';
                $sss .= '<span style="padding-left:100px;"><a style="color:#FF00FF;" href="/index.php?s=/store/zzindb.aligoods/getGoodListTwo/typepid/'.$mainStrArr[0].'/type/'.$sonStrArr[0].'/page/1" target="_blank">一件包邮获取</a></span>';
                $sss .= '</div>';
                echo $sss;
            }
            echo '<hr>';
        }
    }
    /** 获取商品列表入库操作界面 */
    public function getGoodList(){
        $paramArr = $this->request->param();
        $page = !empty($paramArr['page']) ? $paramArr['page'] : 1;
        $type = !empty($paramArr['type']) ? $paramArr['type'] : 0;
        $keyword = !empty($paramArr['keyword']) ? $paramArr['keyword'] : "";
        $typepid = !empty($paramArr['typepid']) ? $paramArr['typepid'] : 0;

        $api = 'com.alibaba.fenxiao:jxhy.product.getPageList-1';
        //echo "***".$keyword; exit;
        $params = [
            'pageNum'=>$page,
            'pageSize'=>50,
            'categoryId'=>$type,
            'priceStart'=>'5',
            'priceEnd'=>'50',
        ];
        if($keyword!=""){
            $params = [
                'keyword'=>$keyword,
                'pageNum'=>$page,
                'pageSize'=>50,
                'categoryId'=>$typepid,
                'priceStart'=>'5',
                'priceEnd'=>'50',
            ];
        }
        $res = $this->getOldData($api, $params);
        //print_r($res); exit;
        $dataArr = $res['result']['result'];
        $bigArr = ['data' => json_encode($dataArr,true),
            'page'=>$page, 'type'=>$type, 'typepid'=>$typepid, 'keyword'=>$keyword,
            'setting'=>11, 'version'=>22, 'store'=>33, 'menus'=>[], 'group'=>33];
        return view('showGood', $bigArr);
    }
    /** 1688严选接口 获取商品列表入库操作一件包邮接口222222222222222 */
    public function getGoodListTwo(){
        $paramArr = $this->request->param();
        $page = !empty($paramArr['page']) ? $paramArr['page'] : 1;
        $type = !empty($paramArr['type']) ? $paramArr['type'] : 0;
        $keyword = !empty($paramArr['keyword']) ? $paramArr['keyword'] : "";
        $typepid = !empty($paramArr['typepid']) ? $paramArr['typepid'] : 0;

        $api = 'com.alibaba.fenxiao:alibaba.pifatuan.product.list-1';
        $params = [
            'pageNo'=>$page,
            'pageSize'=>50,
            'categoryId'=>$type,
            'filterFreePostage' => true,
            'filterYjdf' => true,
            'filter7dNoReasonReturn'=>true,
            'filter48hShip'=>true,
            'filterCommission'=>true,
        ];
        if($keyword!=""){
            $params = [
                'pageNo'=>$page,
                'pageSize'=>50,
                'categoryId'=>$typepid,
                'filterFreePostage' => true,
                'filterYjdf' => true,
                'filter7dNoReasonReturn'=>true,
                'filter48hShip'=>true,
                'filterCommission'=>true,
                'keywords'=>$keyword,
            ];
        }
        $res = $this->getOldData($api, $params);
        $dataArr = $res['result']['result']['resultList'];
        //echo '<pre>';print_r($dataArr); exit;
        $bigArr = ['data' => json_encode($dataArr,true),
            'page'=>$page, 'type'=>$type, 'typepid'=>$typepid, 'keyword'=>$keyword,
            'setting'=>11, 'version'=>22, 'store'=>33, 'menus'=>[], 'group'=>33];
        return view('showGood', $bigArr);
    }
    /** ajax获取已选择的商品信息 */
    public function ajaxGoodToDb(){
        $paramArr = $this->request->param();
        $goodIdStr = !empty($paramArr['goodIdStr']) ? $paramArr['goodIdStr'] : '';
        $type1 = !empty($paramArr['type1']) ? $paramArr['type1'] : 0;
        $type2 = !empty($paramArr['type2']) ? $paramArr['type2'] : 0;

        //此时的$type1和$type2是阿里云的分类id，先需要将查出的商品替换成本系统所需的$type1和$tpye2
        $res111 = Db::name('category')->where(['category_id2'=>$type1, 'wxapp_id'=>$this::wxapp_id])->find();
        $res222 = Db::name('category')->where(['category_id2'=>$type2, 'wxapp_id'=>$this::wxapp_id])->find();
        if(!$res111 || !$res222){
            $back['code'] = 0;
            $back['data'] = null;
            $back['msg'] = '未找到该阿里分类对应的本系统分类，请检查本系统的商品分类表';
            return json_encode($back,true);
            exit;
        }
        else{
            $type1 = $res111['category_id'];
            $type2 = $res222['category_id'];
        }

        if($goodIdStr=="" || $type1==0 || $type2==0){
            $back['code'] = 0;
            $back['data'] = null;
            $back['msg'] = '未选择入库商品';
            return json_encode($back,true);
        }
        else{
            $goodIdArr = explode(',', $goodIdStr);
            $api = 'com.alibaba.fenxiao:alibaba.pifatuan.product.detail.list-2';
            $params = ['offerIds'=>$goodIdArr];
            $res = $this->getOldData($api, $params);
            $aliGoodArr = $res['result']['result'];
            $ableToDbGoodsArr = $this->formatAliGood($aliGoodArr,$type1,$type2);
//            dump($ableToDbGoodsArr);    exit;
            $this->trueGoodInDb($ableToDbGoodsArr);
            $back['code'] = 1;
            $back['data'] = $ableToDbGoodsArr;
            $back['msg'] = '入库成功';
            return json_encode($back,true);
        }
    }
    /** 删除商品及关联数据 谨慎使用 */
    public function delGood(){
        ///store/zzindb.aligoods/delGood/gid/4827/all/yes
        $paramArr = $this->request->param();
        $gid = isset($paramArr['gid']) ? $paramArr['gid'] : 0;
        $all = isset($paramArr['all']) ? $paramArr['all'] : 'no';
        if($gid>0){
            $where = $all=='yes' ? " where goods_id >= $gid" : " where goods_id = $gid";
            $where .= " and wxapp_id=".$this::wxapp_id;
            $sql = "delete from ".getTable('goods'). $where;
            $res = Db::query($sql);

            $where22 = $all=='yes' ? " where back_goodid >= $gid" : " where back_goodid = $gid";
            $where22 .= " and wxapp_id=".$this::wxapp_id;
            $sql22 = "delete from ".getTable('upload_file'). $where22;
            $res22 = Db::query($sql22);

            $where33 = $all=='yes' ? " where goods_id >= $gid" : " where goods_id = $gid";
            $where33 .= " and wxapp_id=".$this::wxapp_id;
            $sql33 = "delete from ".getTable('goods_spec_rel'). $where33;
            $res33 = Db::query($sql33);

            $where44 = $all=='yes' ? " where goods_id >= $gid" : " where goods_id = $gid";
            $where44 .= " and wxapp_id=".$this::wxapp_id;
            $sql44 = "delete from ".getTable('goods_image').$where44;
            $res44 = Db::query($sql44);
            print_r($res44);

            $where55 = $all=='yes' ? " where goods_id >= $gid" : " where goods_id = $gid";
            $where55 .= " and wxapp_id=".$this::wxapp_id;
            $sql55 = "delete from ".getTable('goods_sku'). $where55;
            $res55 = Db::query($sql55);
            print_r($res55);
        }
        else{
            echo '未指定要删除的商品';
        }
    }
    /** 查看商品的阿里巴巴数据 */
    public function aliGoodDesArrPrint(){
        $paramArr = $this->request->param();
        $gid = isset($paramArr['gid']) ? $paramArr['gid'] : 0;
        if($gid>0){
            $api = 'com.alibaba.fenxiao:alibaba.pifatuan.product.detail.list-2';
            $params = ['offerIds'=>[$gid]];
            $res = $this->getOldData($api, $params);
            $aliGoodArr = $res['result']['result'];
            echo '<pre>';print_r($aliGoodArr);
        }
        else{
            echo '未指定要删除的商品';
        }
    }




    /** 将阿里巴巴的数据格式化为通用接口的数据格式入库------------------------------------------------------------------------- */
    private function formatAliGood($aliGoodArr,$type1,$type2){
        $backArr = [];
        foreach($aliGoodArr as $key => $value){
            $productInfo = $value['productInfo'];
            $perGoodArr = [];
            $perGoodArr['id'] = $productInfo['productID']; // 品牌
            $perGoodArr['sellerOpenUid'] = $value['sellerOpenUid'];
            $perGoodArr['state'] = 1; // 1：上架，2：下架
            $perGoodArr['brandId'] = 0; // 品牌
            $perGoodArr['title'] = $productInfo['subject']; // 品牌
            $perGoodArr['vedio'] = !empty($productInfo['detailVedio']) ? $productInfo['detailVedio'] : ""; // mmmodify 需添加字段
            //缩略图要做加前缀处理
            foreach($productInfo['image']['images'] as $kk => $vv){
                $productInfo['image']['images'][$kk] = $this->opmImgStr($vv);
            }
            $mainImg = $productInfo['image']['images'][0];
            $perGoodArr['mainImg'] = $mainImg; // 品牌
            $perGoodArr['goodsCategoryList'][] = ['c1'=>$type1, 'c2'=>$type2, 'c3'=>0]; // 分类
            $perGoodArr['specificationList'] = [];
            //规格信息, 处理最难的规格信息
            $aliSkuInfoArr = !empty($productInfo['skuInfos']) ? $productInfo['skuInfos'] : [];
            $saleInfoArr = $productInfo['saleInfo'];
            $unit = $saleInfoArr['unit'];
            //特殊处理单规格商品
            if(count($aliSkuInfoArr)==0){
                //构造单规格数组
                $aliSkuInfoArr = [
                    0=>[
                        'specId' => $productInfo['productID'],
                        'amountOnSale'=>$saleInfoArr['amountOnSale'],
                        'jxhyPfPrice'=>$saleInfoArr['jxhyPfPrice'],
                        'price'=>$saleInfoArr['priceRanges'][0]['price'],
                        'retailPrice'=>$saleInfoArr['retailprice'],
                        'consignPrice'=>$saleInfoArr['retailprice'],
                        'skuId'=>$productInfo['productID'],
                        'attributes' => [
                            0=>['attributeID'=>$productInfo['productID'],'attributeValue'=>$productInfo['subject']]
                        ]
                    ]
                ];
            }
            foreach($aliSkuInfoArr as $key22 => $value22){
//                if(strlen($productInfo['description'])<65500){
                    $sonSkuGood = [];
                    $sonSkuGood['code'] = $value22['specId'];
                    $sonSkuGood['sellNum'] = $value22['amountOnSale'];
                    $sonSkuGood['currVipPrice'] = $value22['jxhyPfPrice'];    //成本价，分销价
                    $sonSkuGood['detailImgs'] = [];   // mmmodify 详细描述图数组为空，需要特殊判断Ztest入库类
                    $sonSkuGood['detailTxt'] = $productInfo['description'];
                    $sonSkuGood['forbidBuyArea'] = "[]";  // 可购买区域json字符串
                    //echo $value22['specId'].'<br>';
                    // mmmodify zztest中的价格，是含邮费价格的1.1倍，是否需要修改
                    $sonSkuGood['freightPrice'] = $value22['consignPrice'];     // 加上邮费的价格，下单价格 此价格决定关键性售价
                    $sonSkuGood['goodsId'] = $value22['skuId'];
                    $sonSkuGood['imgs'] = $productInfo['image']['images'];
                    $sonSkuGood['isFreeDelivery'] = 1; // 0：不包邮，1：包邮
                    $skuImg = !empty($value22['attributes'][0]['skuImageUrl']) ? $value22['attributes'][0]['skuImageUrl'] : $mainImg;
                    $sonSkuGood['itemMainImg'] = $this->opmImgStr($skuImg);
                    $sonSkuGood['marketIcon'] = 'https://oss-hxq-prod.szbaoly.com/bjsc/comm/tag_sc_price@2x.png';
                    $sonSkuGood['marketPrice'] = floor($value22['retailPrice'] * 2.18);   //市场价
                    $sonSkuGood['minBuyNum'] = $saleInfoArr['minOrderQuantity'];
                    $name = $value22['attributes'][0]['attributeValue'];
                    $sonSkuGood['name'] = $name;
                    $sonSkuGood['remoteAreaFreight'] = "[]";  // 不可购买区域
                    $sonSkuGood['retailPrice'] = $value22['retailPrice'];   //建议零售价
                    $sonSkuGood['specInfo'] = '{"规格":"'.$name.'"}';
                    $sonSkuGood['stepNum'] = 1;
                    $sonSkuGood['stockNum'] = 999999;   //当前库存
                    $sonSkuGood['unit'] = $unit;
                    $sonSkuGood['video'] = '';
                    $sonSkuGood['volume'] = 0;
                    $sonSkuGood['weight'] = 0;

                    $perGoodArr['specificationList'][] = $sonSkuGood;

                    // mmmodify 不论多少规格，只显示20个规格
                    if($key22>29){
                        break;
                    }

//                }
            }
            $backArr[] = $perGoodArr;
        }
//        echo '<pre>';
//        print_r($backArr);
        return $backArr;
    }
    /** 过滤图片文件 */
    private function opmImgStr($img){
        if(strpos($img, 'http')>-1){
            return $img;
        }
        else{
            return 'https://cbu01.alicdn.com/'.$img;
        }
    }








    /** 获取所有商品的1级分类 */
//    public function getType(){
//        $paramArr = $this->request->param();
//        $typeId = !empty($paramArr['type']) ? $paramArr['type'] : 0;
//        $api = 'com.alibaba.product:alibaba.category.get-1';
//        $params = ['categoryID'=>$typeId];
//        $res = $this->getOldData($api, $params);
//        $dataArr = $res['categoryInfo'][0]['childCategorys'];
//        foreach($dataArr as $key => $value){
//            $value['isLeaf'] = $value['isLeaf'] ? 1 : 0;
//            $str = implode('***', $value);
//            echo $str.'<br/>';
//        }
//    }
    /** 将分类入库，只运行一次后将不再运行 */
    public function newTypeInDb(){
        //-------------------------------------入库分类到哪个代理商旗下
        $typeArr = $this->myType;
        $oneSort = 500;
        //ddd($typeArr); exit;
        foreach($typeArr as $value){
            $mainArr = explode('***', $value['mianstr']);
            $inArr11['category_id2'] = $mainArr[0];
            $inArr11['name'] = $mainArr[1];
            $inArr11['sort'] = $oneSort++;
            $inArr11['level'] = 1;
            $inArr11['wxapp_id'] = $this::wxapp_id;
            $inArr11['create_time'] = time();
            $inArr11['update_time'] = time();
            $pppid = Db::name('category')->insertGetId($inArr11);
            $twoSort = 900000;
            foreach($value['sonstrarr'] as $value22){
                $sonStrArr = explode('***', $value22);
                $inArr22['category_id2'] = $sonStrArr[0];
                $inArr22['name'] = $sonStrArr[1];
                $inArr22['parent_id'] = $pppid;
                $inArr22['sort'] = $twoSort++;
                $inArr22['level'] = 2;
                $inArr22['wxapp_id'] = $this::wxapp_id;
                $inArr22['create_time'] = time();
                $inArr22['update_time'] = time();
                Db::name('category')->insertGetId($inArr22);
            }
        }
        dump($typeArr);
    }

}
